package com.nash.demands;

import java.nio.ByteOrder;
import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.EventLog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class DocStockActivity extends Activity {

  public ListView list;
  private EditText ed;
  private Button btnGoods;
  private ToggleButton btnOnlyStock, btnOrder;
  private LayoutInflater mInflater;
  private Cursor data = null;
  DocTabActivity parentActivity = ((DocTabActivity) this.getParent());
  private DecimalFormat df;

  protected long clickedId1;
  private boolean bOnlyStock2;
  private boolean bOnlyOrder;
  private long idGoods2;
  private String tree;

  public void onCreate(Bundle savedInstanceState) {
    try {
      bOnlyOrder = false;
      super.onCreate(savedInstanceState);
      setContentView(R.layout.doc_stocks);
      list = (ListView) findViewById(R.id.listViewStocks);

      list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
          AmountDialog ad = new AmountDialog();
          ad.editAmount(DocStockActivity.this, id);
        }
      });

      ed = (EditText) findViewById(R.id.editTuSearch);
      ed.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
          final SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter) list.getAdapter();
          filterAdapter.setFilterQueryProvider(filterQueryProvider);
          filterAdapter.setStringConversionColumn(1);
          filterAdapter.notifyDataSetChanged();
          filterAdapter.getFilter().filter(s.toString());
        }
      });
      list.setFocusableInTouchMode(true);

      btnGoods = (Button) findViewById(R.id.btnGoodsSelector);

      Long idGoods;
      try {
        idGoods = Long.parseLong(DemandsActivity.getOptionValue("current_goods"));
        idGoods2 = idGoods.longValue();
      } catch (DemandsException e) {
        if (e.getCode() == DemandsException.EX_OPTIONS && e.getCode2() == DemandsException.EX_OPTIONS_NO_FOUND)
          idGoods2 = 1;
        else
          throw e;
      } catch (NumberFormatException e) {
        idGoods2 = 1;
      }
      getTreeAndName();

      btnOnlyStock = (ToggleButton) findViewById(R.id.tglFilter1);

      Long bOnlyStock;
      try {
        bOnlyStock = Long.parseLong(DemandsActivity.getOptionValue("only_stock"));
        bOnlyStock2 = bOnlyStock.longValue() != 0;
        btnOnlyStock.setChecked(bOnlyStock2);
      } catch (DemandsException e) {
        if (e.getCode() == DemandsException.EX_OPTIONS && e.getCode2() == DemandsException.EX_OPTIONS_NO_FOUND)
          bOnlyStock2 = false;
        else
          throw e;
      } catch (NumberFormatException e) {
        bOnlyStock2 = false;
      }
      setTuAdapter();

      btnGoods.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          Intent intent = new Intent(DocStockActivity.this, GoodsActivity.class);
          // Bundle b = new Bundle();
          // b.putLong("demand_id", 0);
          // b.putString("agent_name", currItemOnContextMenuStr);
          // intent.putExtras(b);
          startActivityForResult(intent, DemandsActivity.SELECT_REQUEST_CODE);

        }
      });

      btnOnlyStock.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
          bOnlyStock2 = arg1;
          DemandsActivity.setOption("only_stock", arg1 ? "1" : "0");

          // setTuAdapter();
          final SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter) list.getAdapter();
          filterAdapter.setFilterQueryProvider(filterQueryProvider);
          filterAdapter.setStringConversionColumn(1);
          filterAdapter.notifyDataSetChanged();
          filterAdapter.getFilter().filter(ed.getText());
        }
      });
      df = new DecimalFormat("#0.00");

      btnOrder = (ToggleButton) findViewById(R.id.tglOrder);
      btnOrder.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
          bOnlyOrder = arg1;
          setTuAdapter();
          btnGoods.setEnabled(!bOnlyOrder);
          btnOnlyStock.setEnabled(!bOnlyOrder);
          ed.setEnabled(!bOnlyOrder);
        }
      });

    } catch (Exception e) {
      DemandsException.dialogError(this, e, true);
    }

  }

  private FilterQueryProvider filterQueryProvider = new FilterQueryProvider() {
    @Override
    public Cursor runQuery(CharSequence _constraint) {
      Cursor c;
      StringBuilder sb = new StringBuilder();
      if (bOnlyOrder) {
        sb.append("select tu." + Helper.TBL_TU_NAME + " as NAME,tu." + Helper.TBL_TU_ID_GOODS + ",tu." + BaseColumns._ID + "," + Helper.TBL_TU_STOCK + ", tu.price, tu.nomer, tu.inbox, ti.amount as amount "
            + " from tu," + DocHeadActivity.TBL_TEMP_ITEM + " ti, goods where ti.id_tu=tu._id and tu.id_goods=goods._id and tu.is_arc=0 ");
      } else {
        sb.append("select tu." + Helper.TBL_TU_NAME + " as NAME,tu." + Helper.TBL_TU_ID_GOODS + ",tu." + BaseColumns._ID + "," + Helper.TBL_TU_STOCK + ", tu.price, tu.nomer, tu.inbox, ti.amount as amount "
            + " from tu left join " + DocHeadActivity.TBL_TEMP_ITEM + " ti on (ti.id_tu=tu._id), goods where tu.id_goods=goods._id and tu.is_arc=0 " + (bOnlyStock2 ? (" and " + Helper.TBL_TU_STOCK + ">0") : "")
            + " and goods.tree_str like '");
        sb.append(tree);
        sb.append("%'");
        if (_constraint != null && _constraint.length() > 0) {
          sb.append(" and (tu.name like '%" + _constraint.toString() + "%' or tu.nomer like '%" + _constraint.toString() + "%')");
        }
      }
      sb.append(" order by name asc");
      c = DemandsActivity.db.rawQuery(sb.toString(), null);
      c.moveToFirst();
      startManagingCursor(c);
      return c;
    }
  };

  public void setTuAdapter() {
    String TuFields[] = { Helper.TBL_TU_NAME, Helper.TBL_TU_ID_GOODS, BaseColumns._ID, Helper.TBL_TU_STOCK, "amount" };
    int[] TuTo = new int[] { android.R.id.text1, android.R.id.text2 };

    // StringBuilder sb = new StringBuilder();
    // sb.append("select tu." + Helper.TBL_TU_NAME + " as NAME,tu." +
    // Helper.TBL_TU_ID_GOODS + ",tu." + BaseColumns._ID + "," +
    // Helper.TBL_TU_STOCK +
    // ", tu.price, tu.nomer, tu.inbox, ti.amount as amount "
    // +
    // " from tu left join "+DocHeadActivity.TBL_TEMP_ITEM+" ti on (ti.id_tu=tu._id), goods where tu.id_goods=goods._id and tu.is_arc=0 "
    // + (bOnlyStock2 ? (" and " + Helper.TBL_TU_STOCK + ">0") : "") +
    // " and goods.tree_str like '");
    // sb.append(tree);
    // sb.append("%'");
    // sb.append(" order by name asc");

    data = filterQueryProvider.runQuery(bOnlyOrder?null:ed.getText());

    // data = DemandsActivity.db.rawQuery(sb.toString(), null);
    // startManagingCursor(data);
    list.setAdapter(new TuAdapter(this, android.R.layout.simple_list_item_2, data, TuFields, TuTo));
  }

  private void getTreeAndName() {
    String name;
    if (idGoods2 == 1) {
      tree = "_1_";
      name = "Все группы";
    } else {
      Cursor c = DemandsActivity.db.query(Helper.TBL_GOODS, new String[] { Helper.TBL_GOODS_NAME + " as name", Helper.TBL_GOODS_TREE_STR + " as tree" }, BaseColumns._ID + "=?", new String[] { "" + idGoods2 }, null,
          null, null);
      c.moveToFirst();
      name = c.getString(c.getColumnIndex("name"));
      tree = c.getString(c.getColumnIndex("tree"));
      c.close();
    }
    btnGoods.setText(name);
  }

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DemandsActivity.SELECT_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {
        Bundle b = data.getExtras();
        idGoods2 = b.getLong("id_goods", 0);
        getTreeAndName();
        DemandsActivity.setOption("current_goods", "" + idGoods2);
        String sGoodsName = b.getString("goods_name");

        // setTuAdapter();
        final SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter) list.getAdapter();
        filterAdapter.setFilterQueryProvider(filterQueryProvider);
        filterAdapter.setStringConversionColumn(1);
        filterAdapter.notifyDataSetChanged();
        filterAdapter.getFilter().filter(ed.getText());

        Toast.makeText(this.getApplicationContext(), sGoodsName, Toast.LENGTH_SHORT).show();
      }
    }
  }

  public class TuAdapter extends SimpleCursorAdapter {

    public TuAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
      super(context, layout, c, from, to);
    }

    public void refill(/* List<EventLog> events */) {
      // mEvents.clear();
      // mEvents.addAll(events);
      notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

      ViewHolder holder = null;

      TextView tvName = null;
      TextView tvStock = null;
      TextView tvAmount = null;
      // ImageView iv = null;

      this.getItem(position);
      Cursor rowData = (Cursor) getItem(position);

      if (null == convertView) {
        convertView = mInflater.inflate(R.layout.stock_entry, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
      } //
      holder = (ViewHolder) convertView.getTag();
      tvName = holder.getName();
      tvName.setText(rowData.getString(0));

      tvStock = holder.getStock();
      Integer stock = rowData.getInt(3);
      tvStock.setText("№ " + rowData.getString(5) + "; Упак:" + rowData.getInt(6) + "; Цена: " + df.format(rowData.getFloat(4)) + "; Ост.: " + stock.toString());
      if (rowData.getInt(3) == 0) {
        tvName.setTextColor(0xffff5050);
        tvStock.setTextColor(0xffff5050);
      } else {
        tvName.setTextColor(0xffffffff);
        tvStock.setTextColor(0xffffffff);
      }

      tvAmount = holder.getAmount();
      int amount = rowData.getInt(7);
      tvAmount.setText(amount == 0 ? "" : String.valueOf(amount));
      // tvAmount.setText("150");
      // iv = holder.getImage();
      /*
       * if (rowData.expandable) { if (rowData.expanded)
       * iv.setImageDrawable(getResources
       * ().getDrawable(R.drawable.ic_list_goods_collapse)); else
       * iv.setImageDrawable
       * (getResources().getDrawable(R.drawable.ic_list_goods_expandable)); }
       * else { iv.setImageDrawable(getResources().getDrawable(R.drawable.
       * ic_list_goods_item)); }
       */
      return convertView;
    }
  }

  private class ViewHolder {
    private View mRow;
    private TextView tvName = null;
    private TextView tvStock = null;
    private TextView tvAmount = null;

    // private ImageView iv = null;

    protected ViewHolder(View row) {
      mRow = row;
    }

    protected TextView getName() {
      if (null == tvName) {
        tvName = (TextView) mRow.findViewById(R.id.name_entry);
      }
      return tvName;
    }

    protected TextView getStock() {
      if (null == tvStock) {
        tvStock = (TextView) mRow.findViewById(R.id.item_stock_entry);
      }
      return tvStock;
    }

    protected TextView getAmount() {
      if (null == tvAmount) {
        tvAmount = (TextView) mRow.findViewById(R.id.stock_amount_entry);
      }
      return tvAmount;
    }

    /*
     * protected ImageView getImage() { if (null == iv) { iv = (ImageView)
     * mRow.findViewById(R.id.icon); } return iv; }
     */
  }

}
